package com.zhuzg.common.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源的配置
 */
@Configuration
public class DynamicDataSourceConfig {

        @Autowired
        private DataSourceManager dataSourceManager;

        @Bean
        public DynamicDataSource dynamicDataSource() {
            // 1、将数据源default设置为默认数据源
            DynamicDataSource dynamicDataSource = new DynamicDataSource();
            dynamicDataSource.setDefaultTargetDataSource(
                    dataSourceManager.getDataSource("default"));

            // 2、获取初始化时所有的数据源，并设置目标数据源，必须为targetDataSources设置初始值，否则会报错
            Map<Object, Object> targetDataSources = new HashMap<>();
            targetDataSources.putAll(dataSourceManager.getAllDataSources());
            dynamicDataSource.setTargetDataSources(targetDataSources);
            return dynamicDataSource;
        }

        @Bean
        public DataSourceTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
            return new DataSourceTransactionManager(dynamicDataSource);
        }

}
